import { queryNavTagList, saveNav } from "@/api/content/navigation";
import { uploadFile } from "@/api/file";
import { Navigation } from "@/types/content/navigation";
import { deleteFileInf } from "@/utils/deleteFileInf";
import { PlusOutlined } from "@ant-design/icons";

import {
  Form,
  Input,
  message,
  Modal,
  Radio,
  Select,
  Spin,
  Upload,
  UploadFile,
} from "antd";
import { useForm } from "antd/es/form/Form";
import { useCallback, useEffect, useState } from "react";
interface Props {
  isModalOpen: boolean;
  optionType: "add" | "edit";
  oldInfo?: Navigation.Row;
  close?: () => void;
  change?: () => void;
}
export default function OptionForm(props: Props) {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [loading, setLoading] = useState(false);
  const [form] = useForm();
  const [tagType, setTagType] = useState(0);
  const [messageApi] = message.useMessage();
  const [tagList, setTagList] = useState<string[]>([]);

  const getTagList = useCallback(async () => {
    const res = await queryNavTagList();
    if (res.code === 200) {
      setTagList(res.data || []);
    }
  }, []);
  const uploadFileInf = async (file: File | string | Blob) => {
    if (typeof file === "string") return;
    const formData = new FormData();
    formData.append("file", file);
    try {
      const res = await uploadFile(formData);
      const url = fileList[0] && fileList[0].url ? fileList[0].url : "";
      if (url) {
        deleteFileInf(url);
      }

      if (res.data) {
        setFileList([
          {
            uid: "-1",
            name: "",
            status: "done",
            url: res.data,
          },
        ]);
      }
    } catch (error) {
      console.error(error);
    }
  };
  /**
   * 添加接口
   * @param data
   */
  const saveNavInf = async (data: Navigation.Form) => {
    setLoading(true);
    const res = await saveNav(data);
    setLoading(false);
    if (res.code === 200) {
      messageApi.success("保存成功");
      props.close && props.close();
      props.change && props.change();
    }
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const { name, type, address, description } = values;
      const logo = fileList[0] && fileList[0].url ? fileList[0].url : "";
      const params = {
        name,
        logo,
        type,
        address,
        description,
      };
      if (props.optionType === "add") {
        saveNavInf(params);
      } else if (props.optionType === "edit") {
        saveNavInf({
          ...(props.oldInfo || {}),
          ...params,
          id: props.oldInfo?.id,
        });
      }
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };
  useEffect(() => {
    if (props.optionType === "edit") {
      form.setFieldsValue(props.oldInfo || {});
      props.oldInfo?.logo &&
        setFileList([
          {
            uid: "-1",
            name: "",
            status: "done",
            url: props.oldInfo.logo,
          },
        ]);
    }
  }, [form, props.oldInfo, props.optionType]);
  useEffect(() => {
    getTagList();
  }, [getTagList]);
  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </button>
  );
  return (
    <Modal
      title={props.optionType === "add" ? "新增分类" : "修改分类"}
      open={props.isModalOpen}
      onOk={handleOk}
      onCancel={() => props.close && props.close()}
    >
      <Spin spinning={loading}>
        <Form
          form={form}
          name="categoryOptionForm"
          size="middle"
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item<Navigation.Form>
            name="name"
            label="名称"
            rules={[{ required: true, message: "名称不能为空" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item<Navigation.Form> name="logo" label="logo">
            <Upload
              name="logo"
              listType="picture-card"
              className="avatar-uploader"
              action="#"
              fileList={fileList}
              customRequest={(file) => uploadFileInf(file.file)}
              onRemove={async () => {
                const url =
                  fileList[0] && fileList[0].url ? fileList[0].url : "";
                if (url) {
                  deleteFileInf(url);
                }
                setFileList([]);
              }}
            >
              {fileList.length >= 1 ? null : uploadButton}
            </Upload>
          </Form.Item>

          <Form.Item label="标签类型">
            <Radio.Group
              onChange={(e) => {
                setTagType(e.target.value);
              }}
              value={tagType}
            >
              <Radio value={0}>历史类别</Radio>
              <Radio value={1}>新类别</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item<Navigation.Form>
            name="type"
            label="类别"
            rules={[{ required: true, message: "类别不能为空" }]}
          >
            {tagType === 1 ? (
              <Input />
            ) : (
              <Select
                placeholder="请选择类别"
                style={{ width: 180 }}
                allowClear
                size="middle"
              >
                {tagList.map((item) => (
                  <Select.Option value={item} key={item}>{item}</Select.Option>
                ))}
              </Select>
            )}
          </Form.Item>
          <Form.Item<Navigation.Form>
            name="address"
            label="url"
            rules={[{ required: true, message: "url不能为空" }]}
          >
            <Input.TextArea />
          </Form.Item>
          <Form.Item<Navigation.Form> name="description" label="描述">
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
}
